﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Collections;
using Newtonsoft.Json.Linq;

namespace BEX.Core.Exchange.Coinbase
{
    public class Coinbase : Exchange
    {
        public Coinbase()
            : base(ExchangeType.COINBASE)
        {
            
        }


        internal override Tick GetCurrentTick(CurrencyPair pair)
        {

            
            CoinbaseResponse _resp = GetSpotRate();

            Tick _res = new Tick();

            _res.Spot = Convert.ToInt32(Convert.ToDecimal(_resp.amount) * global.ConversionFactor);
            _res.Currency = pair;
            _res.ExchangeSource = ExchangeType.COINBASE;
            _res.Time = DateTime.UtcNow;

            return _res;

        }

        private CoinbaseResponse GetSpotRate()
        {
            var queryStr = string.Format(TickerURL, string.Empty);
            return new CoinbaseResponse(JObject.Parse(Query(queryStr)) as JObject);
        }

        private static string Query(string url)
        {
            var request = WebRequest.Create(url);
            request.Method = "GET";
            if (request == null)
            {
                throw new Exception("Non HTTP WebRequest");
            }
            return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
        }

        protected override string _baseUrl
        {
            get { return ExchangeConfig.Default.CoinbaseAPI_BaseURL; }
        }

        protected override string _tickPath
        {
            get { return ExchangeConfig.Default.CoinbaseAPI_GetTickPath; }
        }

        protected override string _pairs
        {
            get { return ExchangeConfig.Default.Coinbase_Pairs; }
        }
    }
}
